<template>
  <el-dialog width="400" :title="dialogTitle" v-model="dialogVisible" modal @close="closeDialog" draggable
    :close-on-click-modal="false" :append-to-body="true">
    <el-form class="dialog-form" :model="formData" ref="vForm" label-position="right" label-width="80px" size="medium"
      @submit.native.prevent :rules="formRules">
      <el-form-item label="账号" prop="loginName">
        <el-input v-model="formData.loginName" placeholder="请输入账号" link :disabled="formDisabled" clearable
          autocomplete="off"></el-input>
      </el-form-item>
      <template v-if="!formDisabled">
        <el-form-item label="密码" prop="loginPwd">
          <el-input v-model="formData.loginPwd" placeholder="请输入密码" type="password" show-password
            autocomplete="new-password"></el-input>
        </el-form-item>
        <password v-model="formData.loginPwd" :strength-meter-only="true" @feedback="showFeedback" @score="showScore"
          class="passwordcore" />
      </template>
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="formData.realName" placeholder="请输入姓名" link clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="formData.sex" placeholder="请选择性别" class="full-width-input" clearable>
          <el-option v-for="(item, index) in sexOptions" :key="index" :label="item.label" :value="item.value"
            :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="selectedroles">
        <el-select v-model="formData.selectedroles" placeholder="请选择角色" class="full-width-input" multiple clearable>
          <el-option v-for="(item, index) in roleOptions" :key="index" :label="item.label" :value="item.value"
            :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="selecteddeparts">
        <tree-select v-model="formData.selecteddeparts" :normalizer="tenantIdnormalizer" :options="deptOptions"
          :show-count="true" placeholder="请选择所属部门" :no-options-text="'请前往部门管理添加部门'" />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系方式" link clearable></el-input>
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入电子邮箱" link clearable></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog" size="mini">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, update, getInfo } from '@/api/sys/user'
import { getDictItems } from '@/api/sys/dict'
import { dropDown } from '@/api/sys/role'
// import treeSelect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { ParentDepart } from '@/api/sys/dept'
import Password from 'vue-password-strength-meter'
import rule from '@/utils/rule'

export default {
  name: 'userDialog',
  components: { Password },
  data() {
    return {
      passwordScore: '  低',
      type: '',
      dialogTitle: '',
      dialogVisible: false,
      formData: {},
      formDisabled: false,
      formRules: {
        loginName: [{ required: true, message: '请输入账号', trigger: 'blur' },
        { validator: rule.checkUserName, trigger: 'blur' },

        ],
        loginPwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: rule.checkPassword, trigger: 'blur' },
        ],
        selectedroles: [{ required: true, message: '请选择角色', trigger: 'change' }],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        // phone: [
        //   { required: true, message: '请输入联系方式', trigger: 'blur' },
        //   { validator: rule.validateMobile, trigger: 'blur' },
        // ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
      },
      roleOptions: [],
      sexOptions: [],
      deptOptions: [],
    }
  },
  watch: {
    'formData.selectedroles'(newVal) {
      this.selectedRolesString = newVal.join(',')
    },
  },
  created() {
    this.getSex()
  },
  methods: {
    showFeedback({ suggestions, warning }) { },
    showScore(score) {
      // switch (score) {
      //   case 0:
      //     alert('密码强度低')
      //     break
      //   case 1:
      //     alert('密码强度偏低')
      //     break
      //   case 2:
      //     alert('密码强度中')
      //     break
      //   case 3:
      //     alert('密码强度高')
      //     break
      //   case 4:
      //     alert('密码强度很高')
      //     break
      //   default:
      //     break
      // }
    },
    dropDown() {
      dropDown().then((res) => {
        if (res.data.code === 200) {
          this.roleOptions = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getSex() {
      getDictItems('sex').then((res) => {
        if (res.data.code === 200) {
          this.sexOptions = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 获取树
    getParentDepart() {
      ParentDepart().then((res) => {
        if (res.data.code === 200) {
          this.deptOptions = res.data.data[0].children
        }
      })
    },
    tenantIdnormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.departId,
        label: node.departName,
        children: node.children,
      }
    },
    add() {
      this.dropDown()
      this.getParentDepart()
      this.formDisabled = false
      this.type = 'add'
      this.dialogTitle = '添加用户'
      // 先清空表单数据
      this.formData = {
        selectedroles: [],
      }
      this.dialogVisible = true
    },
    edit(row) {
      this.dropDown()
      this.getParentDepart()
      this.formDisabled = true
      this.type = 'edit'
      this.dialogTitle = '编辑用户'
      getInfo(row.accountId)
        .then((res) => {
          if (res.data.code === 200) {
            this.formData = res.data.data
            this.formData.sex = this.formData.sex.toString()
            if (this.formData.selectedroles) {
              this.formData.selectedroles = this.formData.selectedroles.split(',')
            }
            this.dialogVisible = true
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },

    submitForm() {
      this.$refs['vForm'].validate((valid) => {
        if (valid) {
          this.formData.selectedroles = this.formData.selectedroles.join(',')
          if (this.type === 'add') {
            add(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('添加成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  // this.formData.selectedroles 转为数组
                  this.formData.selectedroles = this.formData.selectedroles.split(',')
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          } else {
            update(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('修改成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          }
        }
      })
    },
    closeDialog() {
      this.$refs['vForm'].resetFields()
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped>
.dialog-form {
  padding: 0 30px;
  /* 根据需求调整数值 */
}

.passwordcore {
  width: calc(100% - 100px);
}
</style>
